<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com> <http://www.jxlnxx.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;
use User\Api\UserApi;
use Discernbank\DiscernBank;
use Api\Model\MemberGiftModel;

/**
 * API用户控制器
 * 主要获取用户数据
 */
class UserController extends ApiController {

    /**
     * 用户登录
     * 
     * @author Ringo Chan<334258471@qq.com>
     */
	public function login(){
	    params_exist(array('user', 'pwd', 'driver'));
	    
	    $username = I('post.user');
	    $password = I('post.pwd');
	    $driver = I('post.driver');
	   
		$user = new UserApi;

		$uid = $user->login($username, $password);

		if(0 < $uid){
			$Member = D('Member');

			if($Member->login($uid)){
			    M('member_token')->where(array('uid'=>$uid, 'deadline' => array('egt', NOW_TIME)))->setField('is_online',0);
				//发货后12天后自动修改为完成状态
				//$order = A('order')->autoTake($uid);
			    $token = addToken($uid, $driver);

				response(1, array('token'=>$token));
			} else {
				response(-1, '', $Member->getError());
			}

		} else {
			switch($uid) {
				case -1: $code = -7; $error = '用户不存在或被禁用！'; break;
				case -2: $code = -1; $error = '密码错误！'; break;
				default: $code = -9; $error = '未知错误！'; break;
			}			
			response($code, '', $error);
		}
	}

	/**
	 * 第三方登录
 	*/
	public function userLoginByThird()
	{
    params_exist(array('openid', 'type', 'nicename', 'avatar'));
    $data = I('');
    $openid = $data['openid'];
    $is_ios = strstr($openid, 'oS-');
    if ($is_ios) {
        $openid = substr($openid, 3);
    }
    $avatar = I('avatar');
    $type = I('type');
    $nickname = I('nicename');
    $where['openid'] = $openid;
    $is_user = M('member')->where($where)->find();

    $User = new UserApi;
    if (!$is_user) {
        $username = $openid;
        $password = '123456';

        $uid = $User->register($username, $password);
        if (0 < $uid) {
            $pic['url'] = $avatar;
            $pic['status'] = 1;
            $pic['create_time'] = time();
            $picid = M('picture')->add($pic);

            $data1 = D('member')->create(array('nickname' => $nickname, 'status' => 1, 'uid' => $uid,'last_login_time'=>time()));
            $data1['login_type'] = $type;
            $data1['openid'] = $openid;
            $data1['avatar'] = $picid;
            D('member')->add($data1);
            $token = addToken($uid, 'wx');
            $mobile = M('ucenter_member')->where('id='.$uid)->getField('username');
            if(is_numeric($mobile)){
            	$is_bind=1;
            }else{
                $is_bind=0;
			}

            response(1, array('token'=>$token,'is_bind'=>$is_bind));
        }else{
            response($uid, '', $this->showRegError($uid));
        }
    }else{
        $mobile = M('ucenter_member')->where('id='.$is_user['uid'])->getField('username');
        if(is_numeric($mobile)){
            $is_bind=1;
        }else{
            $is_bind=0;
        }
        $token = addToken($is_user['uid'], 'wx');
        response(1, array('token'=>$token,'is_bind'=>$is_bind));
	}
}

    /**
     * 用户注册
     * @author Ringo Chan<334258471@qq.com>
     */
	public function register(){
	    
	    params_exist(array('user', 'pwd', 'repwd', 'verify'));
	    
	    $username = I('post.user');
	    $password = I('post.pwd');
	    $repassword = I('post.repwd');
	    $verify = I('post.verify');
	    $referrer = I('post.referrer', 0);
	    
	    empty($verify) && response('-1', '', '验证码不能为空');
	    empty($username) && response('-1', '', '手机号码不能为空');
	    !preg_match('/1[34578]{1}\d{9}$/', $username) && response(-1, '', '请正确输入您的手机号码');
	      empty($password) && response('-1', '', '密码不能为空'); 
	    //!preg_match('/^[a-zA-Z]\w{5,100}$/', $password) && response('-2', '', '密码首字符必须为英文字母');
	    $password != $repassword && response(-2, '', '两次密码输入不一致');
	    $Message_verify = M('Message_verify');
	    $map = array('type'=>'register', 'username'=>$username, 'code'=>$verify, 'deadline'=>array('egt', NOW_TIME), 'status' => 1);
	    $info = $Message_verify->where($map)->find();
	    $info || response('-4', '', '验证码错误,请重新获取输入');
	    /*if (!empty($referrer)) {
	        $referrer2 = M('ucenter_member')->where(array('username'=>$referrer))->getField('id');
	        if(!$referrer2){
                response('-2', '', '推荐人手机号不存在');
			}
	    }*/
	    $ref = M('referrer')->where('mobile='.$username)->find();
	    if($ref){
	    	$uid = M('ucenter_member')->where('usernmae='.$ref['ref_mobile'])->getField('id');
            $referrer=$uid;
		}
	    
        $User = new UserApi;
		$uid = $User->register($username, $password);
		if(0 < $uid){
		    $data1 = D('member')->create(array('nickname' => $username, 'referrer'=>$referrer, 'status' =>1,'uid'=>$uid,'last_login_time'=>time()));
		    D('member')->add($data1);
		    $Message_verify->where($map)->setField('status', 0);
			response(1);
		} else {
			response($uid, '', $this->showRegError($uid));
		}
	}

    /* 密码加密 */
    public function setPass($pass){
        $authcode='rCt52pF2cnnKNB3Hkp';
        $pass="###".md5(md5($authcode.$pass));
        return $pass;
    }
    /**
	 * 找回密码
	 *
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function forgotten(){
	     
	     params_exist(array('user', 'verify'));
	     
	     $username = I('post.user');
	     $verify = I('post.verify');
	      
	     empty($verify) && response('-1', '', '验证码不能为空');
	     empty($username) && response('-1', '', '手机号码不能为空');
	      
	     $Message_verify = M('Message_verify');
	      
	     $map = array(
	         'type'=>'forgotten',
	         'username'=>$username,
	         'code'=>$verify,
	         'deadline'=>array('egt', NOW_TIME),
	         'status' => 1
	     );
	      
	     $info = $Message_verify->where($map)->find();
	     
	     !$info && response('-4', '', '验证码错误,请重新获取输入');
	     
	     $verify = getRandCode(16, 'string');
	     
	     $data = array(
	         'username' => $username,
	         'verify' => $verify,
	         'create_time' => NOW_TIME,
	         'deadline' => NOW_TIME + 1800,
	         'status' => 1
	     );
	     
	     M('Member_forgotten')->add($data) && $Message_verify->where($map)->setField('status', 0);
	     
	     response(1, array('verify'=>$verify));
	}

    /**
     * 绑定手机号
     */
    public function  bindMobile(){
        params_exist(array('mobile', 'verify','openid'));

        $username = I('post.mobile');
        $verify = I('post.verify');
        $openid=I('post.openid');
           $is_ios = strstr($openid,'oS-');
           if($is_ios){
               $openid=substr($openid, 3);
           }
        empty($verify) && response('-1', '', '验证码不能为空');
        empty($username) && response('-1', '', '手机号码不能为空');

        $Message_verify = M('Message_verify');

        $map = array(
            'type'=>'forgotten',
            'username'=>$username,
            'code'=>$verify,
            'deadline'=>array('egt', NOW_TIME),
            'status' => 1
        );

        $info = $Message_verify->where($map)->find();

        !$info && response('-4', '', '验证码错误,请重新获取输入');
        $user=M('ucenter_member')->where('username='.$username)->find();
        if($user){
            response(-9, '', '该手机号已注册或已绑定别的账号');
        }
        $where['openid']=$openid;
        $uid=M('member')->where($where)->getField('uid');

        $maps['username']=$username;
        $maps['update_time']=time();
        $res = M('ucenter_member')->where('id='.$uid)->save($maps);
        //echo M('ucenter_member')->getLastSql();
        if($res){
            response(1);
        } else {
            response(-9, '', '绑定失败');
        }

    }

	/**
	 * 找回密码->设置密码
	 * 
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function resetPassword(){
	    params_exist(array('user', 'verify', 'pwd', 'repwd'));
	    
	    $username = I('post.user');
	    $verify = I('post.verify');
	    $password = I('post.pwd');
	    $repassword = I('post.repwd');
	    
	    empty($verify) && response('-1', '', '验证码不能为空');
	    empty($username) && response('-1', '', '手机号码不能为空');
	    !preg_match('/^[a-zA-Z]\w{6,100}$/', $password) && response('-2', '', '密码首字符必须为英文字母');
	    $password != $repassword && response(-2, '', '两次密码输入不一致');
	    $uid = M('ucenter_member')->where('username='.$username)->find();
	    if(!$uid){
            response(-300, '', '手机号错误，用户不存在');
		}
	    $map = array(
	        'username'=>$username, 
	        'code'=>$verify, 
	        'deadline'=>array('egt', NOW_TIME),
	        'status'=>1
	    );
	    
	    $info = M('Message_verify')->where($map)->find();
	    !$info && response(-4, '', '验证失效');
	    
	    $user = new UserApi();
	    
	    $res = $user->updatePassword($username, $password);
	    
	    if ($res['status']){
	        M('Message_verify')->where($map)->setField('status', 0);
	        response(1);
	    } else {
	        response(-9, '', $res['info']);
	    }
	}
	
	/**
	 * 获取用户昵称
	 * 
	 * @param string token 登录标识
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function getNickname(){
	    !api_login() && response(-94);
	    !passed_login() && response(-95);
	    !only_login() && response(-96);

	    $this->getMemberInfo('nickname');
	}
	
	/**
	 * 编辑用户昵称
	 * 
	 * @param string token 登录标识
	 * @param string nickname
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function editNickname(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    params_exist(array('nickname'));
	    
	    $nickname = I('post.nickname');
	    
	    empty($nickname) && response('-1', '', '昵称不能为空');
		$uid=API_UID;
		$u_member=M('ucenter_member')->where('id='.$uid)->getField('username');
		if(!$u_member){
			response('-2','','用户不存在');
		}
	    $Member = D('Member');
		$data['nickname'] =$nickname;
		$data['update_time'] = time();
	    $Member->where(array('uid'=>$uid))->save($data) ? response(1) : response(-9, '', '更新错误');
	}
	
	/**
	 * 修改用户密码
	 * 
	 * @param string token 登录标识
	 * @param string oldpwd 旧密码
	 * @param string newpwd 新密码
	 * @param string repwd 确认密码
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function editPassword(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    params_exist(array('oldpwd', 'newpwd', 'repwd'));
	    
	    $oldpwd = I('post.oldpwd');
	    $newpwd = I('post.newpwd');
	    $repwd = I('post.repwd');
	    
	    empty($oldpwd) && response(-1, '', '旧密码不能为空');
	    empty($newpwd) && response(-1, '', '新密码不能为空');
	    !preg_match('/^[a-zA-Z]\w{6,100}$/', $newpwd) && response('-2', '', '密码首字符必须为英文字母');
	    $newpwd != $repwd && response(-1, '', '两次密码输入不一致');
	    
	    $user = new UserApi();
	    !$user->verifyUser(API_UID, $oldpwd) && response(-2, '', '旧密码不匹配，请重新输入');
	    
	    $Ucenter_member = M('Ucenter_member');
	    $info = $Ucenter_member->find(API_UID);
	     
	    $user = new UserApi();
	     
	    $res = $user->updatePassword($info['username'], $newpwd);
		//修改直播密码
        $user_pass=$this->setPass($newpwd);
        $data['user_pass']=$user_pass;
        $res=M('users','cmf_')->where('user_login='.$info['username'])->save($data);
	    if ($res){
	        response(1);
	    } else {
	        response(-9, '', $res['info']);
	    }
	}
	
	/**
	 * 获取用户性别
	 * 
	 * @param string token 登录标识
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function getSex(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

	    $this->getMemberInfo('sex');
	}
	
	/**
	 * 修改用户性别
	 * 
	 * @param string token 登录标识
	 * @param integer sex
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function editSex(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	     
	    params_exist(array('sex'));
	    
	    $sex = I('post.sex');
	    
	    !in_array($sex, array(0, 1, 2)) && response(-1, '', '错误性别');

        $uid=API_UID;
        $phone=M('ucenter_member')->where('id='.$uid)->getField('username');
        $data['sex'] = $sex;
        $data['last_login_time'] = date('Y-m-d H:i:s', time());;
        $re = M('users','cmf_')->where('user_login='.$phone)->save($data);

	    $Member = D('Member');
        $data['sex'] =$sex;
        $data['last_login_time']=time();
        $flag=$Member->where(array('uid'=>API_UID))->save($data);
        $flag? response(1) : response(-9, '', '未知错误');
	}
	
	/**
	 * 获取用户手机号码
	 *
	 * @param string token 登录标识
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function getMobile(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	
	    $Ucenter_member = M('Ucenter_member');
	    $info = $Ucenter_member->find(API_UID);
	    
	    $info ? response(1, array('mobile'=>$info['mobile'])) : response(-9);
	}
	
	/**
	 * 修改用户手机号码
	 *
	 * @param string token 登录标识
	 * @param string mobile 更改的手机号
	 * @param string verify 验证码
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function editMobile(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	
	    params_exist(array('mobile', 'verify'));
	    
	    $verify = I('post.verify');
	    $mobile = I('post.mobile');
	    
	    empty($verify) && response('-1', '', '验证码不能为空');
	     
	    $Message_verify = M('Message_verify');
	    
	    $map = array(
	        'type'=>'modifymobile',
	        'username'=>$mobile,
	        'code'=>$verify,
	        'deadline'=>array('egt', NOW_TIME),
	        'status' => 1
	    );
	     
	    $info = $Message_verify->where($map)->find();
	    
	    !$info && response('-4', '', '无效验证码或验证码已过期');
	     
	    !preg_match('/1[3458]{1}\d{9}$/', $mobile) && response(-1, '', '请正确输入您的手机号码');
	    get_table_field($mobile, 'username', 'id', 'ucenter_member') && response(-2, '', '手机号码已注册');
	    
	    $Message_verify->where($map)->setField('status', 0);
	     
	    $Ucenter_member = M('Ucenter_member');
	     
	    $Ucenter_member->where(array('id'=>API_UID))->save(array('mobile'=>$mobile, 'username'=>$mobile)) ? response(1) : response(-9);
	}
	
	/**
	 * 获取收货地址列表
	 * 
	 * @param string token 登录标识
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function getReceiveAddrs(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    $list = array();
	    
	    $Member_receive = M('Member_receive');
	    
	    $results = $Member_receive->where(array('uid'=>API_UID))->order('update_time DESC')->select();
	    
	    foreach ($results as $result) {
	        $list[] = array(
	            'id' => $result['id'],
	            'realname' => $result['realname'],
	            'mobile' => $result['mobile'],
	            'address' => $result['address'],
	            'province_id' => $result['province_id'],
	            'province' => get_table_field($result['province_id'], 'province_id', 'province', 'hat_province'),
	            'city_id' => $result['city_id'],
	            'city' => get_table_field($result['city_id'], 'city_id', 'city', 'hat_city'),
	            'area_id' => $result['area_id'],
	            'area' => get_table_field($result['area_id'], 'area_id', 'area', 'hat_area'),
	            'is_default' => $result['is_default']
	        );
	    }
	    
	    response(1, $list);
	}
	
	/**
	 * 获取用户收货地址详情
	 * 
	 * @param string token 登录标识
	 * @param integer id 收货地址编号
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function getReceiveAddr(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    params_exist(array('id'));
	    
	    $id = I('post.id');
	    
	    $Member_receive = M('Member_receive');
	    
	    $info = $Member_receive->where(array('id'=>$id, 'uid'=>API_UID))->field(array('mobile', 'realname', 'province_id', 'city_id', 'area_id', 'is_default', 'address'))->find();
	    $info['province'] = get_table_field($info['province_id'], 'province_id', 'province', 'hat_province');
	    $info['city'] = get_table_field($info['city_id'], 'province_id', 'city', 'hat_city');
	    $info['area'] = get_table_field($info['area_id'], 'province_id', 'area', 'hat_area');
	    
	    $info ? response(1, $info) : response(-1, '', '没有找到匹配数据');
	}
	
	/**
	 * 删除地址
	 *
	 * @param string token 登录标识
	 * @param integer id 收货地址编号
	 */
	public function delReceiveAddr(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	     
	    params_exist(array('id'));
	     
	    $id = I('post.id');
	     
	    $Member_receive = M('Member_receive');
	     
	    $map=array('id'=>$id, 'uid'=>API_UID);
	    $info = $Member_receive->where($map)->find();
	     
	    empty($info) && response(-1, '', '地址不存在');
	    
	    $Member_receive->where($map)->delete() ? response(1) : response(-9);
	}
	
	/**
	 * 添加用户收货地址
	 * 
	 * @param string token 登录标识
	 * @param string mobile 联系手机号码
	 * @param string realname 姓名
	 * @param integer province_id 省份ID
	 * @param integer city_id 城市ID
	 * @param integer area_id 县\区ID
	 * @param string address 详细地址
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function addReceiveAddr(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    params_exist(array('mobile', 'realname', 'province_id', 'city_id', 'area_id', 'address'));
	    
	    $mobile = I('post.mobile');
	    $realname = I('post.realname');
	    $province_id = I('post.province_id', 0);
	    $city_id = I('post.city_id', 0);
	    $area_id = I('post.area_id', 0);
	    $address = I('post.address');
	    $is_default = I('post.is_default',0);
	    
	    !preg_match('/1[23456789]{1}\d{9}$/', $mobile) && response(-1, '', '请正确输入您的手机号码');
	    !preg_match('/^0|1$/', $is_default) && response(-1, '', '是否为默认地址只能为0或1');
	    !preg_match('/^[\x{4e00}-\x{9fa5}]{1,10}+$/u', $realname) && response(-1, '', '请输入联系人，必须为中文');
	    !get_table_field($province_id, 'province_id', 'province_id', 'Hat_province') && response(-1, '', '选择的省份没有匹配对象');
	    !get_table_field($city_id, 'city_id', 'city_id', 'Hat_city') && response(-1, '', '选择的城市没有匹配对象');
	    !get_table_field($area_id, 'area_id', 'area_id', 'Hat_area') && response(-1, '', '选择的区县没有匹配对象');
	    !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{5,50}+$/u', $address) && response(-1, '', '详细地址长度必须在5~50个字符');
	    	        
	    
	    $data = array(
	        'uid' => API_UID,
	        'realname' => $realname,
	        'mobile' => $mobile,
	        'province_id' => $province_id,
	        'city_id' => $city_id,
	        'area_id' => $area_id,
	        'address' => $address,
	        'is_default' => $is_default,
	        'create_time' => NOW_TIME,
	        'update_time' => NOW_TIME
	    );
	    
	    $Member_receive = M('Member_receive');
	    if($is_default){
	        $Member_receive->where(array('uid'=>API_UID))->setfield('is_default',0);
	    }
	    
	    $Member_receive->add($data) ? response(1) : response(-9);
	}
	
	/**
	 * 编辑用户收货地址
	 *
	 * @param integer id 收货地址编号
	 * @param string token 登录标识
	 * @param string mobile 联系手机号码
	 * @param string realname 姓名
	 * @param integer province_id 省份ID
	 * @param integer city_id 城市ID
	 * @param integer area_id 县\区ID
	 * @param string address 详细地址
	 * @author Ringo Chan<334258471@qq.com>
	 */
	public function editReceiveAddr(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	     
	    params_exist(array('id', 'mobile', 'realname', 'province_id', 'city_id', 'area_id', 'address'));
	    
	    $id = I('post.id');
	    $mobile = I('post.mobile');
	    $realname = I('post.realname');
	    $province_id = I('post.province_id', 0);
	    $city_id = I('post.city_id', 0);
	    $area_id = I('post.area_id', 0);
	    $address = I('post.address');
	    $is_default = I('post.is_default',0);
	    
	    $Member_receive = M('Member_receive');
	   
	    !$Member_receive->where(array('id'=>$id, 'uid'=>API_UID))->find() && response(-1, '', '参数ID错误');
	    
	    !preg_match('/^0|1$/', $is_default) && response(-1, '', '是否为默认地址只能为0或1');
	    !preg_match('/1[23456789]{1}\d{9}$/', $mobile) && response(-1, '', '请正确输入您的手机号码');
	    !preg_match('/^[\x{4e00}-\x{9fa5}]{1,10}+$/u', $realname) && response(-1, '', '请输入联系人，必须为中文');
	    !get_table_field($province_id, 'province_id', 'province_id', 'Hat_province') && response(-1, '', '选择的省份没有匹配对象');
	    !get_table_field($city_id, 'city_id', 'city_id', 'Hat_city') && response(-1, '', '选择的城市没有匹配对象');
	    !get_table_field($area_id, 'area_id', 'area_id', 'Hat_area') && response(-1, '', '选择的区县没有匹配对象');
	    !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $address) && response(-1, '', '详细地址长度必须在5~50个字符');
	    //!preg_match('/^.{5,50}+$/', $address) && response(-1, '', '详细地址长度必须在5~50个字符');
	     
	    $data = array(
	        'id' => $id,
	        'realname' => $realname,
	        'mobile' => $mobile,
	        'province_id' => $province_id,
	        'city_id' => $city_id,
	        'area_id' => $area_id,
	        'address' => $address,
	        'is_default' => $is_default,
	        'update_time' => NOW_TIME
	    );	     
	    if($is_default){
	        $Member_receive->where(array('uid'=>API_UID))->setfield('is_default',0);
	    }    
	    	    
	    $Member_receive->save($data) ? response(1) : response(-9);
	}
	
	/**
	 * 获取用户注册错误信息
	 * 
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
	    switch ($code) {
	        case -1:  $error = '用户名长度必须在16个字符以内！'; break;
	        case -2:  $error = '用户名被禁止注册！'; break;
	        case -3:  $error = '用户名被占用！'; break;
	        case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
	        case -5:  $error = '邮箱格式不正确！'; break;
	        case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
	        case -7:  $error = '邮箱被禁止注册！'; break;
	        case -8:  $error = '邮箱被占用！'; break;
	        case -9:  $error = '手机格式不正确！'; break;
	        case -10: $error = '手机被禁止注册！'; break;
	        case -11: $error = '手机号被占用！'; break;
	        default:  $error = '未知错误';
	    }
	    return $error;
	}
	
	/**
	 * 获取用户字段值
	 * 
	 * @param string $field 字段属性
	 * @return string 字段值
	 * @author Ringo Chan<334258471@qq.com>
	 */
	private function getMemberInfo($field){
	    $Member = D('Member');
	     
	    $info = $Member->where(array('uid'=>API_UID))->find();
	     
	    $info ? response(1, array('nickname'=>$info[$field])) : response(-9, '', '未知错误');
	}

	/**
	 * 我的钱包
	 */
	public function Mywallet(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
	    
	    $result=array();
	    $map=array();
	    $map['uid']=API_UID;
	    
	    $wallet=M('member')->where(array('uid'=>API_UID))->field('uid,amount')->find();
	    
	    response(1,$wallet);
	}

	/**
	 * 用户头像
	 */
    public function avatarPath(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $M_member=M('member');
        $user_info=$M_member->where(array('uid'=>API_UID))->find();
        $avatar=M('picture')->where('id='.$user_info['avatar'])->getField('url');
        if(!$avatar){
        	$avatar='';
		}
        $user_info ? response(1,array('avatar_path'=>$avatar)) : resourcebundle_count(-2);
    }
    
    /**
     * 修改头像
     * @param int cover_id
     */
    public function modifyAvatar(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        $url=I('post.url');
        empty($url) && response('-1', '', '头像地址不能为空');
		/*$url = M('picture')->where('id',$id)->getField('path');
		if(!$url){
            response('-1', '', '头像更新失败');
		}*/
        $data['avatar'] = C('BASE_URI').$url;
        $data['update_time'] = time();
		$res =M('member')->where('uid='.$uid)->save($data);
		$res?response(1) : response(-9);
    }
    
    /*
     * 获取用户基本信息
     */
    public function BaseInfo()
    {
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        $Member = M('Member');
		$uid= API_UID;
        $info = $Member->where(array('uid' => $uid))->find();
        $userinfo =array();
        if($info){
            $userinfo['uid'] = $info['uid'];
            $userinfo['coin'] = $info['coin'];
            $userinfo['amount'] = $info['amount'];

            $userinfo['coin'] = $info['coin'];
            $userinfo['avatar'] = $info['avatar'];
//            $userinfo['avatar_path'] =  M('Picture')->where('id='.$info['avatar'])->getField('path');
           $username= M('ucenter_member')->where(array( 'id' => $uid ))->getField('username');
           if($username ==$info['nickname'] ){
               $userinfo['nickname'] = substr_replace($info['nickname'],'****',3,4);
		   }else {
               $userinfo['nickname'] = $info['nickname'];
           }
           $userinfo['username'] = substr_replace($username,'****',3,4);
        }
       
        $ext_info=M('ucenter_member')->where(array( 'id' => $uid ))->field('username')->find();

        if($userinfo  && $ext_info){
       //     $userinfo=array_merge($userinfo,$ext_info);
        }

        $userinfo && response(1,$userinfo) && response(-2);
    }

	/**
	 * 赠送转让Go或元宝
	 * type 1 元宝 2 惠Go币
	 */
	public function givecoin(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
		//--uid 赠送给谁那个用户 id score_num 赠送数量
		params_exist(array('touid','num','type'));
		//--赠送数量
		$num = (int)I('post.num');
        //赠送类型
		$type = I('type');
        //--赠送给谁
        $touid = I('post.touid');
		if($num<1){
			response(-1,'', '赠送数量不能小于1');
		}

        if($touid == $uid){
            response(-1,'', '不能赠送给自己');
        }

        $ucenter_member = M('ucenter_member')->where('id='.$uid)->find();
        if(!$ucenter_member){
            response(-1,'', '输入的用户id错误，没有找到用户');
        }

        $member = M('member')->where('uid='.$uid)->find();
		if($type ==1 ){ //元宝
			if($num>$member['coin']){
                response(-1,'','您的元宝数量不足');
			}
			//增加对方元宝数量
			$inc_res =M('member')->where('uid='.$touid)->setInc('coin',$num);
			if($inc_res) {
                //赠送记录
                $give_data['uid'] = $uid;
                $give_data['touid'] = $touid;
                $give_data['num'] = $num;
                $give_data['money_type'] = 1;
                $give_data['type'] = 1;
                $give_data['uptime'] = time();
                $give_id2 = M('giverecord')->add($give_data);

                //获赠记录
                $togive_data['uid'] = $touid;
                $togive_data['touid'] = $uid;
                $togive_data['num'] = $num;
                $togive_data['money_type'] = 1;
                $togive_data['type'] = 2;
                $togive_data['uptime'] = time();
                $give_id = M('giverecord')->add($togive_data);

                payrecord($touid,$give_id2,$num,7,0); //获增消费记录
            }

			//减少赠送人元宝数量
            $dec_res=M('member')->where('uid='.$uid)->setDec('coin',$num);
			if($dec_res) {
                payrecord($uid,$give_id,$num,6,0); //转增记录
            }

			if($inc_res && $dec_res){
                response(1,'','赠送成功');
			}else{
                response(-2,'','赠送失败');
			}

		}else{ //惠go币
			if(!$member['is_exchange']){
                response(-1, '','你没有权限转赠金币，请联系客服！');
			}

            if($num>$member['amount']){
                response(-1, '','您的惠Go币数量不足');
            }

            //增加对方惠go币数量
            $inc_res=M('member')->where('uid='.$touid)->setInc('amount',$num);
            //赠送记录
			if($inc_res) {
                $give_data['uid'] = $uid;
                $give_data['touid'] = $touid;
                $give_data['num'] = $num;
                $give_data['money_type'] = 2;
                $give_data['type'] = 1;
                $give_data['uptime'] = time();
                $give_id = M('giverecord')->add($give_data);
            }

            //获赠记录
            if($inc_res){
                $togive_data['uid'] = $touid;
                $togive_data['touid'] = $uid;
                $togive_data['num'] = $num;
                $togive_data['money_type'] = 2;
                $togive_data['type'] = 2;
                $togive_data['uptime'] = time();
                $give_id = M('giverecord')->add($togive_data);
            }
            //减少赠送人惠go币数量
            $dec_res=M('member')->where('uid='.$uid)->setDec('amount',$num);

            //邀请奖励处理
            $member = M('member')->where('uid='.$touid)->find();
            if($member['referrer']) {
                $refer = M('member')->where('uid='.$member['referrer'])->find();
                if($refer){
                    $coin=$num*10;
                    M('member')->where('uid='.$member['referrer'])->setInc('coin',$coin);
                    //邀请奖励记录
                    $refer_data['uid']=$member['referrer'];
                    $refer_data['order_no']=time();
                    $refer_data['type']   = 5;
                    $refer_data['money']  =$coin;
                    $refer_data['month']  = date('Ym',time());
                    $refer_data['status'] = 1;
                    $refer_data['b_refer'] = $touid;
                    $refer_data['createtime']=time();
                    $re = M('user_trade')->add($refer_data);
                }
            }

            if($inc_res && $dec_res){
                response(1,'','赠送成功');
            }else{
                response(-2,'','赠送失败');
            }
		}
	}

    /**
     * 转增记录
     */
	public function giveRecord(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;

         //元宝转增记录
		$c_map['uid']= $uid;
		$c_map['money_type'] =1;
		$coin_list = M('giverecord')->where($c_map)->order('uptime desc ')->select();
		foreach ($coin_list as &$coin){
			if($coin['type'] ==1){
				$msg = "你赠送给ID为".$coin['touid']."的用户".$coin['num']."个元宝";
			}else if($coin['type'] ==2){
                $msg = "你收到了ID为".$coin['touid']."的用户".$coin['num']."个元宝";
			}

			$coin['msg'] = $msg;
			$coin['uptime'] =date('Y/m/d H:i', $coin['uptime']) ;
		}
		//惠go币转增记录
        $c_map['uid']= $uid;
        $c_map['money_type'] =2;
        $go_list = M('giverecord')->where($c_map)->order('uptime desc')->select();
        foreach ($go_list as &$coin){
            if($coin['type'] ==1){
                $msg = "你赠送给ID为".$coin['touid']."的用户".$coin['num']."个惠Go币";
            }else if($coin['type'] ==2){
                $msg = "你收到了ID为".$coin['touid']."的用户".$coin['num']."个惠Go币";
            }
            $coin['msg'] = $msg;
            $coin['uptime'] =date('Y/m/d H:i', $coin['uptime']) ;
        }
		$result['coin_list']= $coin_list?$coin_list:array();
		$result['go_list'] = $go_list?$go_list:array();
        response(1,$result);
	}

	/**
	 * 充值接口
	 */
	public function recharge(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        $money = I('post.money', 0);
        $type = I('post.type');
        $order_no = build_order_no();
		//充值记录
		$data['uid'] = $uid;
        $data['order_no'] = $order_no;
        $data['amount'] = $money;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $data['money_type'] = 2;
        $data['type'] = $type;
        $amount = M('member')->where('uid='.$uid)->getField('amount');
        $data['balance'] = $amount;
        $data['eff_time'] = strtotime('+ 5 minute');
		$res = M('recharge_order')->add($data);
      // payrecord($uid,$order_no,$money,1);

        $result['order_no'] = $order_no;
        response(1,$result);
	}

    /**
     * 充值记录
     */
	public function  recharge_trade(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        $map['uid'] = $uid;
        $map['status'] =1;
        $result =M('recharge_order')->where($map)->order('create_time desc')->select();
        foreach ($result as &$res){
			$res['username'] = M('ucenter_member')->where('id='.$res['uid'])->getField('username');
			$res['create_time'] = date('Y-m-d', $res['create_time']);
			if($res['type'] ==1){
				$res['type_txt'] = '支付宝支付';
			}else if($res['type'] ==2){
                $res['type_txt'] = '微信支付';
            }else if($res['type'] ==3){
                $res['type_txt'] = 'qq支付';
            }else if($res['type'] ==4){
                $res['type_txt'] = '代理支付';
            }else if($res['type'] ==5){
                $res['type_txt'] = '平台充值';
            }
            if($res['money_type']==1) {
                $res['txt'] = "余额：" . $res['balance'] . "元宝";
            }else if($res['money_type']==2){
                $res['txt'] = "余额：" . $res['balance'] . "惠Go币";
			}
		}
		response(1,$result);
	}

    /**
     * 我的二维码
     */
    public function myqrcode(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        $driver = I('post.driver');
        $code= M('member')->where('uid='.$uid)->getField('qrcode');
        if($code){
          //  $data['qrcode'] =$code;
         //   $data['share_url'] = C('BASE_URI')."/api/Invitingfriends/myqrcodepage.html?qrcode=".$code;
       //     response(1,$data);
        }

        $url = C('BASE_URI')."/api/Invitingfriends/index.html?uid=".$uid."&driver=".$driver;
        $filename=time().$uid;
        $qrcode  = qrcode($url,$filename);
        $qrcode = substr($qrcode,1);
        $logo = C('BASE_URI').'/Uploads/qrcode/logo.png';//准备好的logo图片
        $QR = C('BASE_URI').$qrcode;//已经生成的原始二维码图
        if ($logo !== FALSE){
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
		//输出图片
		$imgurl='/Uploads/qrcode/logo'.$uid.time().'.png';
		imagepng($QR,'.'.$imgurl);

        $data['qrcode']= C('BASE_URI').$imgurl;
        $res= M('member')->where('uid='.$uid)->save($data);
      //  $data['share_url'] = C('BASE_URI')."/api/Invitingfriends/myqrcodepage.html?qrcode=". C('BASE_URI').$qrcode;
    
        
        $res? response(1,$data) : response(-9,'','邀请码生成失败');
    }


    /**
     * 我的邀请
     */
    public function invitation(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $map['type'] = 5;
        $map['status'] = 1;
        $map['uid'] = $uid;
		$invitation = M('user_trade')->where($map)->field('sum(money) as money,b_refer')->order('createtime desc')->group('b_refer')->select();
		//echo  M('user_trade')->getLastSql();
		foreach ($invitation as &$inv){
			$avatar=M('member')->where('uid='.$inv['b_refer'])->getField('avatar');
            $inv['avatar'] =  $avatar?$avatar:'';
		}

        $inv_count =M('user_trade')->where($map)->group('b_refer')->select();
        $summoney =M('user_trade')->where($map)->sum('money');
        $result['my_inv']=$invitation?$invitation:array();
        $result['inv_count']= count($inv_count);
        $result['summoney'] = $summoney?$summoney:0;
        //排行榜
		$where['type'] =5;
		$where['status'] =1;
		$where['b_refer'] = array('neq',0);
        $ranking = M('user_trade')->where($where)->field('id,b_refer,SUM(money) as money')->order('money desc')->group('b_refer')->select();

		foreach ($ranking as &$rak){
			$rak['avatar']= M('member')->where('uid='.$rak['b_refer'])->getField('avatar');
            $rak['inv_count'] =M('member')->where('referrer='.$rak['b_refer'])->count();
		}

		$result['ranking'] = $ranking?$ranking:array();
		response(1,$result);
	}

    /**
     * 消费记录
     */
	public function user_trade(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $map['uid'] = $uid;
        $page = I('post.page', 1);
        $page_size = I('post.page_size', 10);
        $offset = ($page - 1) * $page_size;
        $total = M('user_trade')->where($map)->count() | 0;

        $list = M('user_trade')->where($map)->limit($offset, $page_size)->order('createtime desc')->select();
        foreach ($list as $key=>&$li){
            $list[$key]['createtime'] = date('Y-m-d H:i:s', $li['createtime']);
        	if($li['type'] == 1){
                $list[$key]['type_txt'] = "充值";
                $list[$key]['money'] = "+".$li['money'];
			}else  if($li['type'] == 2){
                $list[$key]['type_txt'] = "下注";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 3){
                $list[$key]['type_txt'] = "中奖";
                $list[$key]['money'] = "+".$li['money'];
            }else  if($li['type'] == 4){
                $list[$key]['type_txt'] = "兑换商品";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 5){
                $list[$key]['type_txt'] = "推广";
                $list[$key]['money'] = "+".$li['money'];
            }else  if($li['type'] == 6){
                $list[$key]['type_txt'] = "转增";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 7){
                $list[$key]['type_txt'] = "获赠";
                $list[$key]['money'] = "+".$li['money'];
            }
		}
		$member  = M('member')->where('uid='.$uid)->find();
		//$list['coin'] = $member['coin'];
        $data['total'] = $total;
        $data['list'] = $list;
		$data['coin'] = $member['coin'];
        response(1,$data);
	}

    /**
     * 更改转盘的用户状态
     */
	public function change_exchange(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid = API_UID;
        $type = I('type');
        $map['is_exchange'] = $type;
        $map['update_time'] = time();
        $result = M('member')->where('uid='.$uid)->save($map);
        response(1,$result,'更改成功');
	}

    /**
     * 根据uid获取手机号
     */
	public function getPhone(){
        $uid = I('uid');
        $username=M('ucenter_member')->where('id='.$uid)->getField('username');
        if(!$username){
            response(-9,'','用户不存在');
		}
        $data['phone'] = $username;
        response(1,$data,'操作成功');
	}

}

?>
